/**   
 * Copyright © 2018 Zuxia. Tech Ltd. All rights reserved.
 * 
 * @Package: com.java46.struts2.base.interceptor 
 * @author: zuxia   
 * @date: 2018年7月4日 上午11:07:39 
 */
package com.java46.struts2.base.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.java46.struts2.base.action.BaseAction;
import com.java46.struts2.base.entity.GenericResult;
import com.java46.struts2.base.exception.BusinessException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/** 
 * @ClassName: ExceptionInterceptor 
 * @Description: 异常拦截器
 * @author: zuxia
 * @date: 2018年7月4日 上午11:07:39 
 */
public class ExceptionInterceptor extends AbstractInterceptor {
	
	private final static Logger LOGGER = LogManager.getLogger(ExceptionInterceptor.class);
	
	/** 序列化   **/
	private static final long serialVersionUID = 9120100255275935845L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		try {
			String result = invocation.invoke();
			return result;
		} catch (Exception e) {
			LOGGER.error("统一异常处理", e);
			
			String errorMessage;
			if(e instanceof BusinessException) {
				BusinessException be = (BusinessException) e;
				errorMessage = be.getErrorMessage();
			}else {
				errorMessage = "系统开了会小差，正殴打程序猿！";
			}
			
//			HttpServletRequest request = ServletActionContext.getRequest();
//			if(!this.isAjaxRequest(request)) {// 不是ajax请求
//				request.setAttribute("errorMessage", errorMessage);
//				// 所有的出现异常情况统一返回input
//				return "input";
//			}else {
				GenericResult result = new GenericResult();
				result.setSuccess(false);
				result.setErrorMessage(errorMessage);
				
				BaseAction baseAction = (BaseAction) invocation.getAction();
				baseAction.setResult(result);
				return "json";
//			}
		}
	}
	
	/**
	 * @Title: isAjaxRequest 
	 * @Description: 用于判断请求是否是ajax请求 
	 * @param request
	 * @return boolean  如果return true表示是ajax请求，否则是普通请求
	 * @author zuxia
	 * @date 2018年7月5日上午9:13:01
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		if("XMLHttpRequest".equalsIgnoreCase(ajaxFlag)) {
			return true;
		}
		return false;
	}
	
}
